package com.sxj.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 石小俊
 */
public class Test10_事务处理 {

    public static void main(String[] args) {
        User user = new User("test", "123456", "13612365478", "江苏-南京");
        addUser(user);
    }


    public static void addUser(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            // 开启事务
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user(username,password,phone,address) ")
                    .append(" values(?,?,?,?) ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.executeUpdate();
            int i = 1 / 0;
            System.out.println("提示:恭喜您,添加成功");

            // 提交事务
            conn.commit();
        } catch (SQLException e) {
            // 回滚事务
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new DataAccessException("事务回滚失败");
            }
            throw new DataAccessException("数据访问异常");
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new DataAccessException("事务回滚失败");
            }
            e.printStackTrace();
            System.out.println("错误:服务器内部异常");
        } finally {
            // 对于不需要释放的资源,其值直接给null即可
            JDBCUtil.close(conn, ps, null);
        }
    }

}
